package com.rzico.sbl.ui.report.manager

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.FragmentManagerThirdBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.viewmodel.ReportManagerViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.NavigationFragment
import com.xinnuo.common_ui.base.addItems
import org.json.JSONObject

class ManagerThirdFragment : NavigationFragment() {

    private var mBinding: FragmentManagerThirdBinding? = null

    private var mSaleBeginDate = getBeforeDate(6)
    private var mSaleEndDate = getTodayDate()
    private var mGoodsBeginDate = getBeforeDate(6)
    private var mGoodsEndDate = getTodayDate()
    private val mGoodsList = ArrayList<ManagerDate>()

    override fun getViewModel() = get<ReportManagerViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentManagerThirdBinding
        .inflate(inflater, container, false)
        .also { mBinding = it }
        .root

    /**
     * 初始化
     */
    override fun initTitle() {
        initListener()

        mBinding?.let {
            it.managerChart.apply {
                initChart()

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mGoodsList.indices) ""
                    else mGoodsList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }
    }

    /**
     * 监听方法
     */
    private fun initListener() {
        mBinding?.apply {
            saleAll.oneClick { startActivityEx<ReportThird2Activity>() }
            goodsAll.oneClick { startActivityEx<ReportThirdActivity>() }

            saleTime.addTimeListener { start, end, _ ->
                mSaleBeginDate = start
                mSaleEndDate = end

                getViewModel().cancelRequest()
                getSaleData()
            }

            goodsTime.addTimeListener { start, end, _ ->
                mGoodsBeginDate = start
                mGoodsEndDate = end

                getViewModel().cancelRequest()
                getData()
            }
        }
    }

    override fun onResume() {
        super.onResume()

        getSaleData()
        getData()
    }

    /**
     * 设置曲线图数据
     */
    private fun setGoodsData() {
        mGoodsList.sumOf {
            it.subPrice.doubleValue
        }.apply {
            mBinding
                ?.goodsTotal
                ?.text = (this > 0)
                .conditionElseValue(
                    actionTrue = { " (总: ${formatDecimal()})" },
                    actionFalse = { "" }
                )
        }

        mBinding
            ?.managerChart
            ?.apply {
                (mGoodsList.none { it.subPrice.doubleValue != 0.0 })
                    .conditionElse(
                        actionTrue = ::clear,
                        actionFalse = {
                            setSingleData(
                                entries = mGoodsList.mapIndexed { index, data ->
                                    Entry(
                                        index.toFloat(),
                                        data.subPrice.floatValue
                                    )
                                },
                                lineColor = Color.parseColor("#2486F8"),
                                labelColor = Color.parseColor("#5115FD"),
                                highColor = Color.parseColor("#2486F8"),
                                drawableFill = R.drawable.fade_blue,
                                valueColor = Color.parseColor("#5115FD"),
                                formatter = CustomValueFormatter()
                            )
                        }
                    )

                animateY(500)
            }
    }

    /**
     * 销量统计
     */
    private fun getSaleData() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = ReportUrl.getBaseUrl().zSaleSum,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "beginDate" to mSaleBeginDate,
                    "endDate" to mSaleEndDate
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    mBinding?.apply {
                        saleNum.text = obj.optNotNull("subQuantity")
                        saleAmount.text = obj.optNotNull("subPrice").formatDecimal()
                    }
                }
            )
    }

    /**
     * 商品统计
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsList(
                beginDate = mGoodsBeginDate,
                endDate = mGoodsEndDate,
                onSuccess = {
                    mGoodsList.clear()
                    mGoodsList.addItems(it)

                    setGoodsData()
                }
            )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

}